import { IncomingMessage, ServerResponse } from 'http'
import { ViteDevServer } from 'vite'
import { MockOptions, DEFAULT_OPTIONS } from './type'
import { shouldMock, createMockContext, loadMockData, sendResponse, handleError } from './utils'

/**
 * Mock中间件
 * @param options 配置选项
 */
export default function mockMiddleware(options: MockOptions = {}) {
  const mergedOptions: Required<MockOptions> = { ...DEFAULT_OPTIONS, ...options }

  return {
    name: 'vite-plugin-mock-api',
    configureServer(server: ViteDevServer) {
      server.middlewares.use(
        async (req: IncomingMessage, res: ServerResponse, next: () => void) => {
          try {
            // 检查是否需要mock
            if (!shouldMock(req, mergedOptions)) {
              return next()
            }
            const mockContext = createMockContext(req, res, mergedOptions)

            // 加载mock数据
            const mockData = await loadMockData(mockContext, server)
            if (!mockData) {
              return next()
            }

            // 发送响应
            await sendResponse(mockContext, mockData)
          } catch (error) {
            handleError(error, res, mergedOptions)
          }
        }
      )
    },
  }
}
